package org.paic.vertx.httpwrapper.session;

import redis.clients.jedis.Jedis;

public class JedisSessionStore implements SessionOpter {
	private static Object lock;

	private static JedisSessionStore instance;

	private JedisSessionStore(String host) {
		client = new Jedis(host);
	}

	public static JedisSessionStore getInstance(String host) {
		synchronized (lock) {
			if (instance == null)
				instance = new JedisSessionStore(host);
		}
		return instance;
	}

	private Jedis client;
	private static final String VISIT_KEY = "sessionLastVisited";

	// default 10 minutes
	private long intervalExpired = 1000 * 60 * 10;

	public void setIntervalExpired(long intervalExpired) {
		this.intervalExpired = intervalExpired;
	}

	@Override
	public String get(String key, String name) {
		if (isExpired(key)) {
			clear(key);
			return null;
		}

		return client.hget(key, name);
	}

	@Override
	public void set(String key, String name, String val) {
		client.hset(key, name, val);
	}

	@Override
	public void del(String key, String name) {
		client.hdel(key, new String[] { name });
	}

	@Override
	public void setVisit(String key) {
		set(key, VISIT_KEY, "" + System.currentTimeMillis());
	}

	@Override
	public boolean isExpired(String key) {
		String str = client.hget(key, VISIT_KEY);
		if (str == null)
			return true;

		Long lastVisitedMillis = Long.valueOf(str);
		if(lastVisitedMillis == null)
			return false;
		
		long now = System.currentTimeMillis();
		return now - lastVisitedMillis > intervalExpired;
	}

	@Override
	public void clear(String key) {
		client.del(key);
	}

}
